/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package db

// register the Client driver
import (
	"fmt"

	"hundsun.com/hsl/hschain/common/types"

	"hundsun.com/hsl/hschain/common/config"
)

type dbCreate func(cfg *config.PluginConfig) (Database, error)

var regDB = make(map[string]dbCreate)

// Register 注册 Database driver
func Register(name string, create dbCreate) {
	if create == nil {
		panic("dbCreate: Register driver is nil")
	}
	if _, dup := regDB[name]; dup {
		panic(fmt.Sprintf("dbCreate: driver %s has Registered\n", name))
	}
	regDB[name] = create
}

// NewDataBase 根据名称创建不同类型DB
func NewDataBase(cfg *config.PluginConfig) (Database, error) {
	creator, ok := regDB[cfg.Name]
	if !ok {
		fmt.Printf("dbCreate: Register have not find %s driver", cfg.Name)
		return nil, types.ErrNotFound
	}
	c, err := creator(cfg)
	if err != nil {
		return nil, err
	}
	return c, nil
}
